import router from './router'
import store from './store/index'
const whiteList = ['/login', '/auth-redirect']

router.beforeEach(async(to, from, next) => {
  // document.title = to.meta.title
  const hasToken = localStorage.getItem('thisToken')
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 获取动态权限菜单
      const hasRoles = store.getters.setRouter && store.getters.setRouter.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          const accessedRoutes = await store.dispatch('addRouter')
          accessedRoutes.forEach(element => {
            router.addRoute(element)
          })
          console.log(router.getRoutes())
          next({ ...to, replace: true })
        } catch (error) {
          console.log(error)
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }

  // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  // const getToken = localStorage.getItem('thisToken')

//   if (getToken) {
//     if (to.path === '/login') {
//       next({
//         path: '/'
//       })
//     } else {
//       next()
//     }
//   } else {
//     if (whiteList.indexOf(to.path) !== -1) {
//       next()
//     } else {
//       next(`/login`)
//     }
//   }
})

router.afterEach(() => {
  // finish progress bar
  // NProgress.done()
})
